﻿using BLL.Base;
using BLL.custom;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI;

namespace BLL
{
    /// <summary>
    /// 条码业务逻辑处理
    /// </summary>
    public class BarBLL : SysFrameWork.PubMethod
    {
        Commands cmd;
        LoginInfo userLogin;
        Tools.TxtLogHelper txt;
        ReturnResult rsl;
        OperateModel oper;
        List<OperateModel> operList;

        public BarBLL()
        {
            cmd = new Commands();
            userLogin = new LoginInfo();
            txt = new Tools.TxtLogHelper();
            oper = new OperateModel();
        }
        /// <summary>
        /// 条码数据保存
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public ReturnResult OldSaveBarCode(string data)
        {
            rsl = new ReturnResult();
            try
            {
                string userCode = "";
                var json = JsonConvert.DeserializeObject<DbProductBar>(data);

                #region 保存条码
                if (string.IsNullOrWhiteSpace(json.createuser))
                {
                    userCode = userLogin.UserInfo().userCode;
                }
                else
                {
                    userCode = json.createuser;
                }
                operList = new List<OperateModel>();
                OperateModel oper;
                StringBuilder sb = new StringBuilder();

                string code = CreateBarCode("BP", "条码编码");//统一codeType，方便使用流水号。防止期初和生产条码由于codeType不同，流水号均从1开始，导致条码相同的情况

                //json.happenDate = getNowDate();
                json.barCode = code;
                json.createtime = getNow();

                //是否期初数据
                if (json.isInitial!=null && json.isInitial == "Y")
                {
                    json.isInitial = "Y";
                    json.barType = "QC";
                }
                else
                {
                    json.isInitial = "N";
                    json.barType = "SC";
                }

                json.createuser = userCode;
                json.status = "Y";
                json.barStatus = "need-out";

                json.unit = "kg";

                oper = new OperateModel();
                oper.Data = json;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);

                #endregion

                var msg = "";
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);

                    //保存条码成功后，生产打码的（非期初条码）需要调用入库接口
                    if (rsl.Result)
                    {
                        if (json.isInitial == null || json.isInitial != "Y")   //修改为插件实际所传字段
                        {
                            #region  调用产成品入库接口
                            TOrder t = new TOrder();
                            //rsl.Result = true;
                            rsl = t.productReceive(json);
                            if (!rsl.Result)
                            {
                                msg = rsl.Message;
                                rsl.Message = "入库失败," + msg;
                                txt.AddLogMsg("入库参数" + JsonConvert.SerializeObject(json));
                                txt.AddLogMsg("入库失败," + msg);
                                return rsl;
                            }
                            #endregion

                            #region  生成入库记录
                            SysFrameWork.SystemBLL sysBLL = new SysFrameWork.SystemBLL();
                            var baseCode = sysBLL.getDefaultBaseCode();

                            #region 构建参数数组
                            var cCode = getTimeString();//单据的临时编码
                            Dictionary<string, object> tempdic = new Dictionary<string, object>();
                            tempdic.Add("mCode", cCode);//临时编码
                            tempdic.Add("type", "piw");
                            tempdic.Add("baseCode", baseCode);
                            #endregion

                            #region 添加主表和子表出入库记录
                            operList = new List<OperateModel>();
                            var tempbarCodes = string.Empty;//存入到出入库列表中的条码
                            insertMain(tempdic, json, ref operList);
                            rsl = insertList(tempdic, json, ref operList, ref tempbarCodes, null);
                            if (!rsl.Result)
                            {
                                return rsl;
                            }
                            #endregion

                            #region 执行修改语句
                            rsl = cmd.MoreUpdate(operList);
                            if (!rsl.Result)
                            {
                                return rsl;
                            }
                            #endregion
                            
                            #endregion

                            rsl.Message = "入库成功";
                            txt.AddLogMsg("入库成功");
                        }

                        rsl.Data = code;
                    }
                    else
                    {
                        msg = rsl.Message;
                        rsl.Message = "条码保存失败," + msg;
                    }
                    
                }
                else
                {
                    rsl.Message = "没有要打印的数据";
                }
                return rsl;

            }
            catch (Exception ex)
            {
                txt.AddLogMsg("SaveBarCode程序异常错误：" + ex.Message + "入参：" + data);
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 条码数据保存
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public ReturnResult SaveBarCode(string data)
        {
            rsl = new ReturnResult();
            try
            {
                string userCode = "";
                var json = JsonConvert.DeserializeObject<DbProductBar>(data);
                OperateModel oper=new OperateModel();
                #region 构建条码数据
                if (string.IsNullOrWhiteSpace(json.createuser))
                {
                    userCode = userLogin.UserInfo().userCode;
                }
                else
                {
                    userCode = json.createuser;
                }
                operList = new List<OperateModel>();
                
                StringBuilder sb = new StringBuilder();
             
                string code = CreateBarCode("BP", "条码编码");//统一codeType，方便使用流水号。防止期初和生产条码由于codeType不同，流水号均从1开始，导致条码相同的情况
                json.barCode = code;
                json.createtime = getNow();
                //是否期初数据
                if (json.isInitial != null && json.isInitial == "Y")
                {
                    json.isInitial = "Y";
                    json.barType = "QC";
                }
                else
                {
                    json.isInitial = "N";
                    json.barType = "SC";
                }

                json.createuser = userCode;
                json.status = "Y";
                json.barStatus = "need-out";
                json.unit = "kg";

                #endregion

                string status = "Y";
                if (json.isInitial != null && json.isInitial == "N")
                {
                    #region 非期初条码 需生成T+产成品入库
                    TOrder t = new TOrder();
                    rsl = t.productReceive(json);
                    if (!rsl.Result)
                    {
                        if (!string.IsNullOrWhiteSpace(rsl.Message) && rsl.Message.IndexOf("失效") > -1)
                        {
                            #region 出现token失效情况 需重新获取token 然后二次进行提交入库
                            AutoTaskBLL auto = new AutoTaskBLL();
                            txt.AddLogMsg("token失效，开始重新获取token");
                            auto.auto_token("N");//非自动任务调用
                            rsl = t.productReceive(json);
                            if (!rsl.Result)
                            {
                                #region 二次调用接口仍然失败，不在重复执行方法
                                status = "N";
                                txt.AddLogMsg(String.Format("二次入库失败，错误消息：{0},参数：{1}", JsonConvert.SerializeObject(rsl), JsonConvert.SerializeObject(json)));
                                #endregion
                            }
                            #endregion
                        }
                        else
                        {//其他情况入库失败
                            status = "N";
                            txt.AddLogMsg(String.Format("入库失败，错误消息：{0},参数：{1}", rsl.Message, JsonConvert.SerializeObject(json)));
                            return rsl;
                        }
                    }
                    #endregion
                }
                if (!rsl.Result)
                {
                    json.status = status;
                    json.memo = "无效";
                }
                oper.Data = json;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);

                #region  生成入库记录
                SysFrameWork.SystemBLL sysBLL = new SysFrameWork.SystemBLL();
                var baseCode = sysBLL.getDefaultBaseCode();

                #region 构建参数数组
                var cCode = getTimeString();//单据的临时编码
                Dictionary<string, object> tempdic = new Dictionary<string, object>();
                tempdic.Add("mCode", cCode);//临时编码
                tempdic.Add("type", "piw");
                tempdic.Add("baseCode", baseCode);
                #endregion

                #region 添加主表和子表出入库记录
                //operList = new List<OperateModel>();
                var tempbarCodes = string.Empty;//存入到出入库列表中的条码
                insertMain(tempdic, json, ref operList);
                rsl = insertList(tempdic, json, ref operList, ref tempbarCodes, null);
                if (!rsl.Result)
                {
                    return rsl;
                }
                #endregion
                #endregion

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                    if (rsl.Result)
                    {
                        rsl.Data = code;
                        txt.AddLogMsg("入库成功");
                    }
                    else
                    {
                        rsl.Message = "条码保存失败";
                        txt.AddLogMsg(rsl.Message);

                    }
                }
                else
                {
                    rsl = new ReturnResult();
                    rsl.Result = false;
                    rsl.Message = "没有要打印的数据";
                    txt.AddLogMsg(rsl.Message);
                }
                return rsl;

            }
            catch (Exception ex)
            {
                txt.AddLogMsg("SaveBarCode程序异常错误：" + ex.Message + "入参：" + data);
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 提交无效条码
        /// </summary>
        public void SubmitLostBar()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from bar_ProductBarCode_info where status='N'");
                var barTable = cmd.GetDataTable(sb.ToString());
                var list= cmd.TableToDictionary(barTable);
                foreach (var r in list)
                {
                    var db = JsonConvert.DeserializeObject<DbProductBar>(JsonConvert.SerializeObject(r));
                    TOrder t = new TOrder();
                    rsl = t.productReceive(db);
                    if (rsl.Result)
                    {
                        sb.Clear();
                        sb.Append("update bar_ProductBarCode_info set status='Y',memo='" + getNow() + "'");
                        sb.Append(" where id=" + r["id"]);
                        txt.AddLogMsg("自动提交无效条码，执行sql：" + sb.ToString());
                        cmd.UpdateSql(sb.ToString());
                    }
                    else
                    {
                        txt.AddLogMsg("无效条码入库依旧失败，关联条码:" + r["barCode"] + "错误消息："+JsonConvert.SerializeObject(rsl)) ;
                    }
                    Thread.Sleep(1000);//程序暂停1秒
                }
            }
            catch (Exception ex)
            {
                txt.AddLogMsg("自动更新无效条码程序异常(SaveBarInfo)：" + ex.Message);
            }
        }


        /// <summary>
        /// 出入库记录单主表
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="qList"></param>
        /// <param name="list"></param>
        public void insertMain(Dictionary<string, object> dic, DbProductBar qList, ref List<OperateModel> list)
        {
            #region 反写出入库记录的主表
            var type = dic["type"].ToString();
            var mCode = dic["mCode"].ToString();//临时编码
            var baseCode = dic["baseCode"].ToString();//
            DbBarRecordsMain main = new DbBarRecordsMain();
            main.happenDate = qList.happenDate;
            main.wareHouse = qList.wareHouse;
            main.isBlue = "1";
            main.createuser = qList.createuser;
            main.createtime = getNow();
            main.baseCode = baseCode;
            main.status = "needAudit";
            main.maker = qList.createuser;
            main.inOutType = type;
            main.mCode = mCode;//主表的临时码
            main.isForm = "app";//数据来源
            OperateModel oper = new OperateModel();
            oper.Data = main;
            oper.Types = OperateModel.OperateType.Add;
            list.Add(oper);
            txt.AddLogMsg("反写出入库记录主表单据号：" + mCode);
            #endregion
        }

        /// <summary>
        /// 出入库记录子表
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="qList"></param>
        /// <param name="list"></param>
        /// <param name="barCodes"></param>
        /// <param name="erridList"></param>
        /// <returns></returns>
        public ReturnResult insertList(Dictionary<string, object> dic, DbProductBar qList, ref List<OperateModel> list, ref string barCodes, List<string> erridList)
        {
            #region 反写出入库单据明细表的数据
            var type = dic["type"].ToString();
            var mCode = dic["mCode"].ToString();//临时编码
            var baseCode = dic["baseCode"].ToString();
            rsl = new ReturnResult();

            string barCode = qList.barCode;

            DbBarRecordsList dl = new DbBarRecordsList();
            dl.barCode = barCode;
            dl.mCode = mCode;//主表临时编码
            dl.status = "Y";
            dl.createuser = qList.createuser;
            var listCount = cmd.GetDataByObject<DbBarRecordsList>(dl).Count;
            if (listCount <= 0)
            {
                #region list数据
                dl.barCode = barCode;
                dl.createtime = getNow();
                dl.mCode = mCode;//主表临时编码
                dl.num = qList.proWeight;
                dl.inOutType = type;
                OperateModel oper = new OperateModel();
                oper.Data = dl;
                oper.Types = OperateModel.OperateType.Add;
                list.Add(oper);
                #endregion
            }

            rsl.Result = true;
            #endregion
            return rsl;
        }


        public static string SerializeObject<T>(T value, JsonSerializerSettings settings)
        {
            if (value == null)
            {
                return null;
            }

            var dictionaryObject = new Dictionary<string, object> { { typeof(T).Name, value } };
            var jsonString = JsonConvert.SerializeObject(dictionaryObject, settings);

            return jsonString;
        }

        public static T DeserializeObject<T>(string jsonString, JsonSerializerSettings settings)
        {
            var objectValue = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString, settings);
            return JsonConvert.DeserializeObject<T>(objectValue.Values.First().ToString(), settings);
        }


        /// <summary>
        /// 条码数据列表展示
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getBarCodeList(string pageIndex, string pageSize, ref string pageCount, string condition, string orderStr)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                #region 检索条件
                sb.Append(" baseCode='" + userLogin.UserInfo().baseCode + "' ");//and barStatus<>'bar-drop' 
                sb = CreateSelectCondition(sb, condition);
                #endregion
                if (string.IsNullOrWhiteSpace(orderStr))
                {
                    orderStr = "id desc";
                }
                var list = cmd.PageList("V_BarCode_Info", pageIndex, pageSize, sb.ToString(), orderStr, ref pageCount);
                
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }



        public ReturnResult getBarCodeInList(string pageIndex, string pageSize, ref string pageCount, string condition, string orderStr)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" baseCode='" + userLogin.UserInfo().baseCode + "' and barStatus='need-in' ");
                sb.Append(" and barCode not in(select barCode from bar_TempScanData_info)");
                sb = CreateSelectCondition(sb, condition);
                if (string.IsNullOrWhiteSpace(orderStr))
                {
                    orderStr = "id desc";
                }
                var list = cmd.PageList<ViewBarCodeInfo>("V_BarCode_Info", pageIndex, pageSize, sb.ToString(), orderStr, ref pageCount);

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 在库条码
        /// </summary>
        /// <param name="condition">检索条件</param>
        /// <returns></returns>
        public ReturnResult BarInWareHouse(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                sb.Append("select barCode,proCode,proName,spec,number,'' planZy from V_BarCode_Info where barStatus='need-out' and");
                sb.Append(" proCode='" + json["proCode"].ToString() + "' and baseCode='" + userLogin.UserInfo().baseCode + "'");
                var barTable = cmd.GetDataTable(sb.ToString());

                sb.Clear();
                sb.Append("select b.barCode,po.plCode from pi_ProductOccupy_info po ");
                sb.Append("inner join V_BarCode_Info b on b.barCode=po.barCode ");
                sb.Append("and b.barStatus='need-out' and b.proCode='" + json["proCode"].ToString() + "'");
                sb.Append("  and b.baseCode='" + userLogin.UserInfo().baseCode + "' ");
                sb.Append("where po.isdel=0");
                var zyTable = cmd.GetDataTable(sb.ToString());//条码占用
                foreach (DataRow r in barTable.Rows)
                {
                    var dr = zyTable.Select("barCode='" + r["barCode"].ToString() + "'");
                    if (dr.Length > 0)
                    {
                        r.BeginEdit();
                        r["planZy"] = dr[0]["plCode"].ToString();
                        r.BeginEdit();
                    }
                }
                rsl.Data = cmd.TableToDictionary(barTable);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 条码编码生成方法
        /// </summary>
        /// <param name="codeType">条码类型</param>
        /// <param name="memo">备注</param>
        /// <returns></returns>
        /// 

        public ReturnResult getBoxCodeList(string pageIndex, string pageSize, ref string pageCount, string condition, string orderStr)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" barStatus<>'bar-drop' ");
                sb = CreateSelectCondition(sb, condition);
                if (string.IsNullOrWhiteSpace(orderStr))
                {
                    orderStr = "id desc";
                }
                var list = cmd.PageList("V_BoxCode_Info", pageIndex, pageSize, sb.ToString(), orderStr, ref pageCount);

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

      

        public string CreateBarCode(string codeType, string memo)
        {
            try
            {
                int barLength = int.Parse(Tools.ConfigReader.Reader["CodeLength"]);
                StringBuilder sb = new StringBuilder();
                sb.Append("select parValue from sys_parameters_info where ");
                sb.Append("parCode='BarCodeLeng' and isDel=0 and enable='open'");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    barLength = int.Parse(table.Rows[0][0].ToString());
                }
                var code = CreateCodeInfo(codeType, memo, barLength);
                return code;
            }
            catch (Exception ex)
            {
                txt.AddLogMsg("createCode方法异常：" + ex.Message);
            }
            return null;
        }

        /// <summary>
        ///  通过条码获取存货信息
        /// </summary>
        /// <param name="barCode">条码编码</param>
        /// <returns></returns>
        public ReturnResult getProductInfoByBarCode(string barCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_BarCode_Info where ");
                sb.Append("barCode='" + barCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "该条码不存在";
                }

            }
            catch (Exception ex)
            {
                txt.AddLogMsg("方法异常(getProductInfoByBarCode)：" + ex.Message);
            }
            return rsl;
        }
        /// <summary>
        /// 条码占用信息
        /// </summary>
        /// <param name="barCode">占用条码(允许为空)</param>
        /// <returns></returns>
        public ReturnResult GetBarZhanYongInfo(string barCode)
        {

            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select *  from V_ProductOccupy_info");
                sb.Append(" where isdel=0");
                if (!string.IsNullOrWhiteSpace(barCode))
                {
                    sb.Append(" and barCode='" + barCode + "'");
                }
                var list = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;

        }


        /// <summary>
        /// 条码出入库记录列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getBarEntryRecords(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                #region
                StringBuilder sb = new StringBuilder();
                sb.Append(" 1=1 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "sDate")
                            {
                                sb.Append("convert(date,happendate)>='" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "eDate")
                            {
                                sb.Append("convert(date,happendate)<='" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }
                #endregion
                var list = cmd.PageList("V_BarEntoryRecords_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                for (int i = 0; i < list.Count; i++)
                {
                    sb.Clear();
                    sb.Append("select  l.barcode,isnull(b.proWeight,0) number,b.unitName from  bar_BarEntryRecords_list l ");
                    sb.Append("left join V_BarCode_Info b on l.barCode=b.barCode ");
                    sb.Append("where l.status='Y' and l.mCode='" + list[i]["mCode"] + "'");
                    var table = cmd.GetDataTable(sb.ToString());
                    double numTotal = 0; string unitName = "";
                    foreach (DataRow r in table.Rows)
                    {
                        numTotal += double.Parse(r["number"].ToString());
                        unitName = r["unitName"].ToString();
                    }
                    if (list[i]["inOutTypeName"].Contains("入库"))
                    {
                        list[i]["inWeight"] = numTotal.ToString();
                        list[i]["inBarCodeCount"] = table.Rows.Count.ToString();
                    }
                    else if (list[i]["inOutTypeName"].Contains("出库"))
                    {
                        list[i]["outWeight"] = numTotal.ToString();
                        list[i]["outBarCodeCount"] = table.Rows.Count.ToString();
                    }
                    
                }
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据编码获取出入库记录信息
        /// </summary>
        /// <param name="condition">检索条件</param>
        /// <returns></returns>
        public ReturnResult getRecordsListByCode(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_BarEntryRecords_list where ");
                sb.Append("  mCode='" + json["mCode"].ToString().Trim() + "'");
                sb.Append(" and baseCode='" + userLogin.UserInfo().baseCode + "'");
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 销售到货单信息(已审核)
        /// </summary>
        /// <param name="condition">检索条件</param>
        /// <returns></returns>
        public ReturnResult saleWareHousing(string condition)
        {
            rsl = new ReturnResult();
            CuDbHelper cuHelper = new CuDbHelper();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select top 50 m.cCode,convert(varchar(10),m.dDate,120)  as  dDate,s.cInvCode,p.cInvName,");
                sb.Append("p.cInvStd,m.cWhCode,s.iNum,s.iQuantity,s.chVencode,v.cVenName,w.cWhName,");
                sb.Append("cDefine22, mz.cComUnitName mUnitName,cz.cComUnitName cUnitName,isnull(s.cFree7,'') tssx");
                sb.Append(" from Rdrecords01 s inner join inventory p on s.cInvCode=p.cInvCode ");
                sb.Append("inner join Rdrecord01 m on m.id=s.id and m.dVeriDate is not null ");
                sb.Append("inner join ComputationUnit mz on p.cComUnitCode=mz.cComunitCode ");
                sb.Append("inner join ComputationUnit cz on s.cAssUnit=cz.cComunitCode ");
                sb.Append("inner join Warehouse w on w.cWhCode=m.cWhCode ");
                sb.Append("inner join Vendor v on v.cVenCode=s.chVencode ");
                sb.Append(" where 1=1 ");
                #region 检索条件
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "sDate")
                            {
                                sb.Append("convert(date,dDate)>='" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "eDate")
                            {
                                sb.Append("convert(date,dDate)<='" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }


                        }
                    }
                }
                #endregion
                sb.Append(" order by s.autoid desc");
                var table = cuHelper.getData(sb.ToString(), userLogin.UserInfo().baseCode);
                var list = cmd.TableToDictionary(table);
                DonePrint(ref list);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        private void DonePrint(ref List<Dictionary<string, string>> datas)
        {
            StringBuilder sb;
            for (int i = 0; i < datas.Count; i++)
            {
                string orderCode = datas[i]["cCode"].ToString();
                string proCode = datas[i]["cInvCode"].ToString();
                string tssx = datas[i]["tssx"].ToString();
                string d_mnum = "0", d_cnum = "0";
                sb = new StringBuilder();
                sb.Append("select U8relationCode,sum(convert(decimal(18,2),c_gongjin)) mnum,proCode,");
                sb.Append("sum(convert(decimal(18,2),c_mishu)) cnum,c_tssx from bar_ProductBarCode_info ");
                sb.Append("where status='Y' and U8relationCode='" + orderCode + "' and proCode='" + proCode + "'");
                sb.Append(" and barType='chengpin' and c_tssx='" + tssx + "' group by U8relationCode,proCode,c_tssx");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    d_cnum = table.Rows[0]["cnum"].ToString();
                    d_mnum = table.Rows[0]["mnum"].ToString();
                }
                datas[i]["doneCnum"] = d_cnum;
                datas[i]["doneMnum"] = d_mnum;
            }
        }
        /// <summary>
        /// 条码作废
        /// </summary>
        /// <param name="barCode">条码编码</param>
        /// <returns></returns>
        public ReturnResult DropBarCode(string barCode, string userCode = "")
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                if (string.IsNullOrWhiteSpace(barCode))
                {
                    rsl.Message = "没有获取到条码";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();

                sb.Clear();
                sb.Append("select barStatus,barType from bar_ProductBarCode_info where barCode='" + barCode + "'");
                var barTable = cmd.GetDataTable(sb.ToString());
                if (barTable.Rows.Count > 0)
                {
                    //if (barTable.Rows[0]["gxCode"].ToString() != "WG" && barTable.Rows[0]["barStatus"].ToString() != "need-in" && barTable.Rows[0]["barStatus"].ToString() != "")
                    if (barTable.Rows[0]["barType"].ToString() == "NULL" || barTable.Rows[0]["barType"].ToString() == "SC" )
                    {
                        rsl.Message = "此类条码禁止作废";
                        return rsl;
                    }
                }
                #region 改变条码状态
                DbProductBar bar = new DbProductBar();
                bar.barCode = barCode;
                bar.barStatus = "bar-drop";
                bar.status = "N";
                if (string.IsNullOrWhiteSpace(userCode))
                {
                    bar.memo = string.Format("条码作废({0},{1})", userLogin.UserInfo().userCode, getNow());
                }
                else
                {
                    bar.memo = string.Format("条码作废({0},{1})", userCode, getNow());
                }
                oper = new OperateModel();
                oper.Data = bar;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "barCode";
                operList.Add(oper);
                #endregion


                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

       
        /// <summary>
        /// 加载临时数据
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult loadTempData(string condition)
        {
            rsl = new ReturnResult();
            try
            {

                StringBuilder sb = new StringBuilder();
                sb.Append("select *,b.proName,b.spec,b.c_gongjin,b.c_mishu,b.number,b.unitName from bar_TempScanData_info t ");
                sb.Append("inner join V_BarCode_Info b on t.barCode=b.barCode");
                sb.Append(" where 1=1  ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            sb.Append(obj.Name + "='" + obj.Value.ToString() + "' ");
                        }
                    }
                }
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 加载临时扫码数据
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult loadTempScanTotal(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var arr = condition.Split('-');
                string tempCode = "";
                if (arr[0] == "1")
                {//入库
                    tempCode = "P-In" + arr[1];
                }
                else
                {
                    tempCode = "P-Out" + arr[1];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select tempCode,proCode,proName,spec,sum(convert(decimal(18,2),c_gongjin)) gongjin,");
                sb.Append("sum(convert(decimal(18,2),c_mishu)) mishu,count(bt.barCode) barCount,b.c_xilie, ");
                sb.Append("sum(convert(decimal(18,2),b.number)) number,b.unitName,outCompanyName from bar_TempScanData_info bt ");
                sb.Append("inner join V_BarCode_Info b on b.barCode=bt.barCode ");
                sb.Append("where tempCode='" + tempCode + "'  ");
                sb.Append("group by proCode,proName,spec,tempCode,b.unitName,outCompanyName,b.c_xilie ");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除临时扫码数据
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult DelTempScan(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("delete from bar_TempScanData_info where id='" + dataId + "'");
                rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 选码入库方法
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult SubmitInHouse(string tempCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select *  from bar_TempScanData_info where tempCode='" + tempCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 退货回库(只涉及出库，入库不考虑)
        /// </summary>
        /// <param name="mCode"></param>
        /// <returns></returns>
        public ReturnResult BackInWareHouse(string mCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from  V_BarEntryRecords_list where mCode='" + mCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    string wareHouse = table.Rows[0]["wareHouse"].ToString();
                    foreach (DataRow r in table.Rows)
                    {
                        DbProductBar bar = new DbProductBar();
                        bar.barCode = r["barCode"].ToString();
                        bar.wareHouse = wareHouse;
                        bar.barStatus = "need-out";
                        oper = new OperateModel();
                        oper.Data = bar;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "barCode";
                        operList.Add(oper);
                    }
                    if (operList.Count > 0)
                    {
                        rsl = cmd.MoreUpdate(operList);
                    }
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        ///  强制情况条码状态
        /// </summary>
        /// <param name="barCodes">条码集合</param>
        /// <param name="barStatus">更改条码状态</param>
        /// <returns></returns>
        public ReturnResult ResetBarInfo(string datas, string barStatus = null)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                if (string.IsNullOrWhiteSpace(json["barType"].ToString()))
                {
                    rsl.Message = "请选择条码状态";
                    return rsl;
                }
                var arr = json["barCodes"].ToString().Split(',');
                var barCodes = "";
                foreach (string s in arr)
                {
                    barCodes += "'" + s + "',";
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("update bar_ProductBarCode_info set barType='" + json["barType"].ToString() + "' ");

                if (json.Property("barStatus") != null && json["barStatus"].ToString() == "1")
                {
                    sb.Append(",barStatus='' ");
                    if (string.IsNullOrWhiteSpace(barStatus))
                    {
                        sb.Append(",wareHouse='' ");
                    }
                    else
                    {
                        sb.Append(",wareHouse='" + barStatus + "' ");
                    }
                }
                sb.Append("where barCode in(" + barCodes.TrimEnd(',') + ")");
                rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        public ReturnResult DropZhanYong(string barCodes)
        {
            rsl = new ReturnResult();
            try
            {
                var bArr = barCodes.Split(',');
                string bStr = "";
                foreach (string s in bArr)
                {
                    if (!string.IsNullOrWhiteSpace(s))
                    {
                        bStr += "'" + s + "',";
                    }
                }
                bStr = bStr.TrimEnd(',');
                if (!string.IsNullOrWhiteSpace(bStr))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("update pi_ProductOccupy_info set isdel=1,");
                    sb.Append("deluser='" + userLogin.UserInfo().userCode + "',");
                    sb.Append("deldate='" + getNow() + "' where barCode in (" + bStr + ")");
                    rsl = cmd.UpdateSql(sb.ToString());
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        //修改在库条码所在位置（仓库 货位）
        public ReturnResult updateWarePosition()
        {
            rsl = new ReturnResult();
            try
            {
                List<string> list = new List<string>();

                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_wareChange ");
                var table = cmd.GetDataTable(sb.ToString());//需要修改的仓库对照表

                //sb.Clear();
                ////sb.Append("select * from bar_ProductBarCode_info where barStatus = 'need-out' and status='Y' ");
                //sb.Append("select s.color,s.trademark,b.* from bar_ProductBarCode_info b ");
                //sb.Append("inner join bar_ProductBarCode_Sub_info s on s.barCode = b.barCode where barStatus = 'need-out' and status = 'Y' ");
                //var bTable = cmd.GetDataTable(sb.ToString());//在库的条码表

                foreach (DataRow dr in table.Rows)
                {
                    sb.Clear();
                    sb.Append("update bar_ProductBarCode_info set wareHouse='" + dr["targetWare"].ToString() + "',warePosition ='" + dr["targetPos"].ToString() + "' ");
                    sb.Append("where ");
                    if (string.IsNullOrWhiteSpace(dr["positionCode"].ToString()))
                    {
                        sb.Append("wareHouse='" + dr["wareCode"].ToString() + "' and (warePosition ='" + dr["positionCode"].ToString() + "' or warePosition is null )");
                    }
                    else
                    {
                        sb.Append("wareHouse='" + dr["wareCode"].ToString() + "' and warePosition ='" + dr["positionCode"].ToString() + "'");
                    }
                    if (dr["wareCode"].ToString() == "006")
                    {
                        if (string.IsNullOrEmpty(dr["shangbiao"].ToString()))
                        {
                            //sb.Append(" and trademark!='唯本' ");
                            sb.Append(" and barCode in (select barCode from  bar_ProductBarCode_Sub_info where trademark!='唯本' )");
                        }
                        else
                        {
                            sb.Append(" and barCode in (select barCode from  bar_ProductBarCode_Sub_info where trademark ='唯本' ) ");
                        }
                    }else if (dr["wareCode"].ToString() == "011")
                    {
                        if (dr["shangbiao"].ToString() == "all")
                        {
                            sb.Append(" and barCode in (select barCode from  bar_ProductBarCode_Sub_info where trademark not in ('京东京造','简言织','简小益')  ) ");
                        }
                        else
                        {
                            sb.Append(" and barCode in (select barCode from  bar_ProductBarCode_Sub_info where trademark in (" + dr["shangbiao"].ToString() + ") ) ");
                        }
                    }

                    list.Add(sb.ToString());
                }

                if (list.Count > 0)
                {
                    rsl=cmd.MoreUpdate(list);
                }

                return rsl;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

    }


}
